<template>
  <div class="flex gap-1 items-center justify-start">
    <Select
      ref="selectRef"
      size="small"
      v-model="basicConfig"
      :options="props.options"
      filter
      :autoOptionFocus="true"
      optionLabel="name"
      placeholder="Select a Config"
      class="w-full md:w-56"
      @change="codeSelectFn"
    >
      <template #value="slotProps">
        <div v-if="slotProps.value" class="flex items-center">
          <div>{{ slotProps.value.name }}</div>
        </div>
        <span v-else>
          {{ slotProps.placeholder }}
        </span>
      </template>
      <template #option="slotProps">
        <div class="flex items-center">
          <div>{{ slotProps.option.name }}</div>
        </div>
      </template>
    </Select>
    <InputText
      ref="inputRef"
      size="small"
      type="text"
      @keydown.enter="confirm"
      v-model="basicConfigValue"
    />
    <Button icon="pi pi-check" size="small" @click="confirm"></Button>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { useToast } from 'primevue/usetoast'
import type { BasicConfig } from '@/types/dt/Dt.ts'

interface BasicConfigOption {
  name: string
  code: string
}

const selectRef = ref()
const inputRef = ref()
const props = defineProps<{
  options: BasicConfigOption[]
}>()

const toast = useToast()
const basicConfig = ref<BasicConfigOption>()
const basicConfigValue = ref()

const emit = defineEmits<{
  (e: 'confirm', value: BasicConfig): void
}>()
const confirm = () => {
  if (!basicConfig.value || !basicConfigValue.value) {
    toast.add({ severity: 'error', summary: '请填写配置', life: 3000, closable: true })
    return
  }
  emit('confirm', {
    code: basicConfig.value?.code,
    value: basicConfigValue.value,
  })
  basicConfig.value = undefined
  basicConfigValue.value = undefined
  selectRef.value.$refs.focusInput.focus()
}

function codeSelectFn() {
  setTimeout(() => {
    inputRef.value.$el.focus()
  }, 10)
}
</script>

<style scoped></style>
